package com.mdlib.helper.api.network;

import com.ljlib.help.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by librabin on 16/9/28.
 */

public class RetrofitHelper {

    private static OkHttpClient configClient(final boolean haveToken) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }
//        File cacheFile = new File(MDConstant.PATH_CACHE);
//        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        // 设置Token
        if (haveToken) {
            builder.addInterceptor(new CommonParamsInterceptor());
        }
        // 设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        // 错误重连
        builder.retryOnConnectionFailure(true);

        return builder.build();
    }




    public synchronized static  <T> T configRetrofit(Class<T> service, String url, boolean haveToken) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(configClient(haveToken))
                .addConverterFactory(JsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(service);
    }



}
